package com.ruoyi.ncpsy.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.ncpsy.domain.NcpsyCropFertilizer;
import com.ruoyi.ncpsy.domain.NcpsyEventLog;
import com.ruoyi.ncpsy.mapper.NcpsyEventLogMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.config.Config;
import org.fisco.bcos.sdk.config.ConfigOption;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
import org.fisco.bcos.sdk.crypto.keypair.ECDSAKeyPair;
import org.fisco.bcos.sdk.transaction.manager.AssembleTransactionProcessor;
import org.fisco.bcos.sdk.transaction.manager.TransactionProcessorFactory;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ncpsy.mapper.NcpsyPesticideCropMapper;
import com.ruoyi.ncpsy.domain.NcpsyPesticideCrop;
import com.ruoyi.ncpsy.service.INcpsyPesticideCropService;

/**
 * 喷洒农药记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-29
 */
@Service
public class NcpsyPesticideCropServiceImpl implements INcpsyPesticideCropService 
{
    @Autowired
    private NcpsyPesticideCropMapper ncpsyPesticideCropMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private NcpsyEventLogMapper ncpsyEventLogMapper;

    /**
     * 查询喷洒农药记录
     * 
     * @param pesticideCropId 喷洒农药记录主键
     * @return 喷洒农药记录
     */
    @Override
    public NcpsyPesticideCrop selectNcpsyPesticideCropByPesticideCropId(Long pesticideCropId)
    {
        return ncpsyPesticideCropMapper.selectNcpsyPesticideCropByPesticideCropId(pesticideCropId);
    }

    /**
     * 查询喷洒农药记录列表
     * 
     * @param ncpsyPesticideCrop 喷洒农药记录
     * @return 喷洒农药记录
     */
    @Override
    public List<NcpsyPesticideCrop> selectNcpsyPesticideCropList(NcpsyPesticideCrop ncpsyPesticideCrop)
    {
        return ncpsyPesticideCropMapper.selectNcpsyPesticideCropList(ncpsyPesticideCrop);
    }

    /**
     * 新增喷洒农药记录
     * 
     * @param ncpsyPesticideCrop 喷洒农药记录
     * @return 结果
     */
    @Override
    public int insertNcpsyPesticideCrop(NcpsyPesticideCrop ncpsyPesticideCrop) throws Exception {
        ncpsyPesticideCrop.setCreateTime(DateUtils.getNowDate());
        
        // 创建临时目录
        Path tempDir = null;
        try {
            tempDir = Files.createTempDirectory("bcos_sdk_");
            System.out.println("Created temporary directory: " + tempDir.toAbsolutePath());
            
            // 创建临时配置文件
            File tempConfigFile = new File(tempDir.toFile(), "config-example.toml");
            copyResourceToFile("BOOT-INF/classes/config-example.toml", tempConfigFile);
            
            // 创建临时证书目录
            File tempCertDir = new File(tempDir.toFile(), "conf");
            tempCertDir.mkdirs();
            
            // 复制证书文件
            File caCertFile = new File(tempCertDir, "ca.crt");
            copyResourceToFile("BOOT-INF/classes/conf/ca.crt", caCertFile);
            
            File sdkCertFile = new File(tempCertDir, "sdk.crt");
            copyResourceToFile("BOOT-INF/classes/conf/sdk.crt", sdkCertFile);
            
            File sdkKeyFile = new File(tempCertDir, "sdk.key");
            copyResourceToFile("BOOT-INF/classes/conf/sdk.key", sdkKeyFile);
            
            // 创建临时ABI目录
            File tempAbiDir = new File(tempDir.toFile(), "abi");
            tempAbiDir.mkdirs();
            System.out.println("Created temporary ABI directory: " + tempAbiDir.getAbsolutePath());
            
            // 复制ABI文件
            File cropPesticideAbiFile = new File(tempAbiDir, "CropPesticideContract.abi");
            copyResourceToFile("BOOT-INF/classes/abi/CropPesticideContract.abi", cropPesticideAbiFile);
            
            // 修改配置文件中的证书路径
            String configContent = new String(Files.readAllBytes(tempConfigFile.toPath()));
            configContent = configContent.replace("conf/ca.crt", tempCertDir.getAbsolutePath() + "/ca.crt");
            configContent = configContent.replace("conf/sdk.crt", tempCertDir.getAbsolutePath() + "/sdk.crt");
            configContent = configContent.replace("conf/sdk.key", tempCertDir.getAbsolutePath() + "/sdk.key");
            Files.write(tempConfigFile.toPath(), configContent.getBytes());
            
            // 初始化BcosSDK对象
            BcosSDK sdk = BcosSDK.build(tempConfigFile.getAbsolutePath());
            
            // 获取Client对象，此处传入的群组ID为1
            ncpsyPesticideCropMapper.insertNcpsyPesticideCrop(ncpsyPesticideCrop);
            Client client = sdk.getClient(Integer.valueOf(1));
            long user_id = ncpsyPesticideCrop.getUserId();
            String hash = sysUserMapper.selecthashById(user_id);
            System.out.println(hash);
            ECDSAKeyPair ecdsaKeyPair = new ECDSAKeyPair();
            CryptoKeyPair keyPair = ecdsaKeyPair.createKeyPair(hash);
            System.out.println("Using ABI path for TransactionProcessor: " + tempAbiDir.getAbsolutePath());
            AssembleTransactionProcessor transactionProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(client, keyPair, tempAbiDir.getAbsolutePath(), "");
            
            // 创建调用交易函数的参数，此处为传入一个参数
            List<Object> params = new ArrayList<>();
            params.add(ncpsyPesticideCrop.getPesticideCropId().toString());
            params.add(ncpsyPesticideCrop.getCropEventId().toString());
            params.add(ncpsyPesticideCrop.getPesticideId().toString());
            params.add(DateUtils.parseDateToStr("yyyy-MM-dd", ncpsyPesticideCrop.getApplicationDate()));
            TransactionResponse transactionResponse = transactionProcessor.sendTransactionAndGetResponseByContractLoader("CropPesticideContract", "0x8bbd349ae95996a2ea5df511e84d0d4f247e6085", "insert", params);
            
            //获取交易哈希
            String transactionHash = transactionResponse.getTransactionReceipt().getTransactionHash();
            NcpsyPesticideCrop ncpsyPesticideCrop1 = new NcpsyPesticideCrop();
            ncpsyPesticideCrop1.setHash(transactionHash);
            ncpsyPesticideCrop1.setPesticideCropId(ncpsyPesticideCrop.getPesticideCropId());
            ncpsyPesticideCropMapper.updateNcpsyPesticideCrop(ncpsyPesticideCrop1);
            
            //记录农药喷洒事件日志
            NcpsyEventLog ncpsyEventLog = new NcpsyEventLog();
            ncpsyEventLog.setCropEventId(ncpsyPesticideCrop.getCropEventId());
            ncpsyEventLog.setEventType("农药事件");
            ncpsyEventLog.setCreateTime(DateUtils.parseDate(ncpsyPesticideCrop.getCreateTime()));
            
            String eventDescription = "该作物在"+ DateUtils.parseDateToStr("yyyy-MM-dd", ncpsyPesticideCrop.getApplicationDate()) + "进行了农药喷洒操作，使用农药编号为：" + ncpsyPesticideCrop.getPesticideId()+ "，方法为"
                    + ncpsyPesticideCrop.getApplicationMethod() ;
            ncpsyEventLog.setEventDescription(eventDescription);
            ncpsyEventLog.setCreateTime(ncpsyPesticideCrop.getCreateTime());
            ncpsyEventLogMapper.insertNcpsyEventLog(ncpsyEventLog);
            
            return 1;
        } finally {
            // 清理临时目录
            if (tempDir != null) {
                deleteRecursively(tempDir.toFile());
            }
        }
    }

    /**
     * 修改喷洒农药记录
     * 
     * @param ncpsyPesticideCrop 喷洒农药记录
     * @return 结果
     */
    @Override
    public int updateNcpsyPesticideCrop(NcpsyPesticideCrop ncpsyPesticideCrop)
    {
        ncpsyPesticideCrop.setUpdateTime(DateUtils.getNowDate());
        return ncpsyPesticideCropMapper.updateNcpsyPesticideCrop(ncpsyPesticideCrop);
    }

    /**
     * 批量删除喷洒农药记录
     * 
     * @param pesticideCropIds 需要删除的喷洒农药记录主键
     * @return 结果
     */
    @Override
    public int deleteNcpsyPesticideCropByPesticideCropIds(Long[] pesticideCropIds)
    {
        return ncpsyPesticideCropMapper.deleteNcpsyPesticideCropByPesticideCropIds(pesticideCropIds);
    }

    /**
     * 删除喷洒农药记录信息
     * 
     * @param pesticideCropId 喷洒农药记录主键
     * @return 结果
     */
    @Override
    public int deleteNcpsyPesticideCropByPesticideCropId(Long pesticideCropId)
    {
        return ncpsyPesticideCropMapper.deleteNcpsyPesticideCropByPesticideCropId(pesticideCropId);
    }
    
    /**
     * 将类路径下的资源文件复制到临时文件
     * 
     * @param resourcePath 资源路径
     * @param targetFile 目标文件
     * @throws IOException IO异常
     */
    private void copyResourceToFile(String resourcePath, File targetFile) throws IOException {
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
             OutputStream outputStream = new FileOutputStream(targetFile)) {
            
            if (inputStream == null) {
                throw new IOException("Resource not found: " + resourcePath);
            }
            
            // 添加日志输出，以便调试
            System.out.println("Copying resource: " + resourcePath + " to " + targetFile.getAbsolutePath());
            
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            
            // 确认文件复制成功
            System.out.println("Successfully copied resource: " + resourcePath);
        }
    }
    
    /**
     * 递归删除文件或目录
     * 
     * @param file 要删除的文件或目录
     */
    private void deleteRecursively(File file) {
        if (file == null) {
            return;
        }
        
        if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null) {
                for (File child : children) {
                    deleteRecursively(child);
                }
            }
        }
        
        file.delete();
    }
}
